import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('adminToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('adminToken')
      localStorage.removeItem('level')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 创建用户
export const createUser = (data) => {
  return api.post('/user-manage/create', data)
}

// 更新用户
export const updateUser = (data) => {
  return api.put('/user-manage/update', data)
}

// 删除用户
export const deleteUser = (userId) => {
  return api.delete(`/user-manage/delete/${userId}`)
}

// 批量删除用户
export const batchDeleteUser = (userIds) => {
  return api.delete('/user-manage/batch-delete', { data: userIds })
}

// 分页查询用户
export const getUserPage = (queryDTO, pageDTO) => {
  return api.post('/user-manage/page', { queryDTO, pageDTO })
}

// 获取用户详情
export const getUserDetail = (userId) => {
  return api.get(`/user-manage/detail/${userId}`)
}

// 切换用户状态
export const toggleUserStatus = (userId, status) => {
  return api.put(`/user-manage/toggle-status/${userId}`, null, {
    params: { status }
  })
}

// 获取用户列表
export const getUserList = () => {
  return api.get('/user-manage/list')
}

// 分页查询软删除用户
export const getDeletedUsersPage = (pageDTO) => {
  return api.get('/user-manage/deleted-users', { params: pageDTO })
}

// 查看软删除用户（兼容旧接口）
export const getDeletedUsers = () => {
  return api.get('/user-manage/deleted-users')
}

// 恢复用户（需要后端提供此接口）
export const restoreUser = (userId) => {
  return api.put(`/user-manage/restore/${userId}`)
}

// 批量恢复用户（需要后端提供此接口）
export const batchRestoreUsers = (userIds) => {
  return api.put('/user-manage/batch-restore', { userIds })
}

// 查看所有用户（包括软删除的）
export const getAllUsers = () => {
  return api.get('/user-manage/all-users')
} 